//
//  ViewIdentifierModifier.swift
//  NyamanDana
//
//  Created by 李永彬 on 2025/10/17.
//

import SwiftUI

struct ViewIdentifierModifier: ViewModifier {
    let identifier: String
    
    func body(content: Content) -> some View {
        content
            .onAppear {
                setAccessibilityIdentifier(identifier)
            }
    }
    
    private func setAccessibilityIdentifier(_ identifier: String) {
        DispatchQueue.main.asyncAfter(deadline: .now() + 0.3) {
            guard let windowScene = UIApplication.shared.connectedScenes.first as? UIWindowScene else { return }
            
            for window in windowScene.windows {
                if let navigationController = findNavigationController(in: window.rootViewController),
                   let topViewController = navigationController.topViewController {
                    topViewController.view.accessibilityIdentifier = identifier
                    print("✅ 设置视图标识符: \(identifier)")
                    break
                }
            }
        }
    }
    
    private func findNavigationController(in viewController: UIViewController?) -> UINavigationController? {
        guard let viewController = viewController else { return nil }
        
        if let navigationController = viewController as? UINavigationController {
            return navigationController
        }
        
        for child in viewController.children {
            if let navigationController = findNavigationController(in: child) {
                return navigationController
            }
        }
        
        return nil
    }
}
